package lv.solcraft.replication.server.rest.restlets;

import java.io.IOException;

import lv.solcraft.replication.server.api.ServerFacade;
import net.sf.json.JSONArray;

import org.restlet.Context;
import org.restlet.data.CharacterSet;
import org.restlet.data.Encoding;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

import com.noelios.restlet.application.EncodeRepresentation;

public class OperExecutorResource extends Resource {

    private long siteId;

    private ServerFacade serverFacade;

    /** should be injected by Spring automatically */
    public void setServerFacade(ServerFacade serverFacade) {
        this.serverFacade = serverFacade;
    }

    public OperExecutorResource() {
        super();
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        siteId = Long.parseLong(request.getAttributes().get("site").toString());
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }

    @Override
    public boolean allowPost() {
        return true;
    }

    @Override
    public boolean allowGet() {
        return true;
    }

    @Override
    public void handlePost() {
        try {
            JSONArray array = JSONArray.fromObject(getRequest().getEntity().getText());
            serverFacade.updateStatesJSON(siteId, array);
        } catch (IOException e) {
            throw new IllegalStateException("Oper-site update failed, " + e.getMessage(), e);
        }
    }

    @Override
    public Representation getRepresentation(Variant variant) {
        JSONArray jsonArray = serverFacade.getFirstNewOpersJSON(siteId);
        StringRepresentation stringRepresentation = new StringRepresentation(jsonArray.toString(1), MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8);
        return new EncodeRepresentation(Encoding.GZIP, stringRepresentation);
    }
}
